﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Security;

namespace Goldlight.Mvvm.Base
{
    public static class Utility
    {
        /// <summary>
        /// Find the data context for a particular element.
        /// </summary>
        /// <param name="element">The element to find the context for.</param>
        /// <returns>The data context if found, null otherwise.</returns>
        public static object FindDataContext(DependencyObject element)
        {
            if (element is FrameworkElement && ((FrameworkElement)element).DataContext != null)
                return ((FrameworkElement)element).DataContext;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                return FindDataContext(VisualTreeHelper.GetChild(element, i));
            }
            return null;
        }

        /// <summary>
        /// Determine whether or not we have the requested permission.
        /// </summary>
        /// <param name="requestedPermission">The permission to check.</param>
        /// <returns>True if this application has the relevant permission, false otherwise.</returns>
        public static bool CheckPermission(this CodeAccessPermission requestedPermission)
        {
            bool hasPermission = true;

            try
            {
                requestedPermission.Demand();
            }
            catch
            {
                hasPermission = false;
            }
            return hasPermission;
        }
    }
}
